package com.huika.renrench.control.my.merchant;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.my.adapter.MyShopAdapter;
import com.huika.renrench.control.my.adapter.MyShopAdapter.OnCheckItem;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.http.ServerFlagError;
import com.huika.renrench.http.ServerJsonUnParseError;
import com.huika.renrench.support.bean.MyShopListBean;
import com.huika.renrench.view.TitleBarHelper;

/**
 * @ClassName: TransferNewShopActivity
 * @说明:我的店铺转让信息
 * @author zwy
 * @date 2015年6月2日 下午5:50:58
 */
public class MyShopListActivity extends BaseAct implements OnCheckItem, OnRefreshListener2<ListView> {
	private PullToRefreshListView ptrLv;
	private ArrayList<MyShopListBean> myShopListBeans;
	private MyShopAdapter adapter;
	private boolean isEdit = false;
	private TitleBarHelper titleBarHelper;
	private LinearLayout layoutBottom;
	private TextView tvSelect;
	private TextView tvUpdata;
	private TextView tvOut;
	private TextView tvDelete;
	private String actionFlag;
	private LinearLayout layoutNewShop;
	private Button btnNewShop;

	private ArrayList<Integer> delist;// 删除的集合,点完成后清空

	@Override
	protected void initData() {
		delist = new ArrayList<Integer>();
		myShopListBeans = new ArrayList<MyShopListBean>();
	}

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_myshop_list);
	}

	@Override
	protected void initWidget() {
		titleBarHelper = new TitleBarHelper(this, -1, -1, R.string.title_myshop);
		titleBarHelper.setLeftMsg(R.string.left_back);
		titleBarHelper.setOnRightClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isEdit) {
					isEdit = false;
					titleBarHelper.setRightMsg("编辑");
					setEdit();
					ptrLv.setOnItemClickListener(skipItemListener);
				} else {
					isEdit = true;
					titleBarHelper.setRightMsg("完成");
					setEdit();
					ptrLv.setOnItemClickListener(editItemListener);
				}
			}
		});
		ptrLv = (PullToRefreshListView) findViewById(R.id.ptrlv_amsl);
		layoutBottom = (LinearLayout) findViewById(R.id.layout_bottom_amsl);
		tvSelect = (TextView) findViewById(R.id.tv_select_amsl);
		tvUpdata = (TextView) findViewById(R.id.tv_updata_time_amsl);
//		tvOut = (TextView) findViewById(R.id.tv_out_amsl);
		tvDelete = (TextView) findViewById(R.id.tv_delete_amsl);
		layoutNewShop = (LinearLayout) findViewById(R.id.layout_bottom_newshop_amsl);
		btnNewShop = (Button) findViewById(R.id.btn_newshop_amsl);
		tvUpdata.setOnClickListener(this);
		btnNewShop.setOnClickListener(this);
//		tvOut.setOnClickListener(this);
		tvDelete.setOnClickListener(this);
		ptrLv.setOnRefreshListener(this);
		ptrLv.setMode(Mode.BOTH);
		ptrLv.setOnItemClickListener(skipItemListener);

		adapter = new MyShopAdapter(this, this);
		ptrLv.setAdapter(adapter);
		// test();
		showLoadingDialog("");
		listNet();
	}

	@Override
	public void widgetClick(View v) {
		switch (v.getId()) {
		case R.id.tv_updata_time_amsl:
			actionFlag = "1";
			actionNet();
			break;
//		case R.id.tv_out_amsl:
//			actionFlag = "3";
//			actionNet();
//			break;
		case R.id.tv_delete_amsl:
			actionFlag = "2";
			actionNet();
			break;
		case R.id.btn_newshop_amsl:
			showActivity(MyShopListActivity.this, MyShopActivity.class);
			break;

		default:
			break;
		}
	}


	private void setEdit() {
		if (isEdit) {
			// for (int i = 0; i < myShopListBeans.size(); i++) {
			// MyShopListBean bean = myShopListBeans.get(i);
			// bean.setEidt(true);
			// adapter.notifyDataSetChanged();
			// }
			layoutBottom.setVisibility(View.VISIBLE);
			layoutNewShop.setVisibility(View.GONE);
			adapter.showCbs();
		} else {
			// for (int i = 0; i < myShopListBeans.size(); i++) {
			// MyShopListBean bean = myShopListBeans.get(i);
			// bean.setEidt(false);
			// adapter.notifyDataSetChanged();
			// }
			layoutBottom.setVisibility(View.GONE);
			layoutNewShop.setVisibility(View.VISIBLE);
			adapter.hideCbs();
		}
	}

	@Override
	public void onCheckItem(int position, boolean isChecked) {
		if (isChecked) {
			delist.add(Integer.valueOf(position));
		} else {
			delist.remove(Integer.valueOf(position));
		}
		MyShopListBean bean = myShopListBeans.get(position);
		bean.setCheck(isChecked);
		tvSelect.setText(String.format("已选择（%s）", String.valueOf(delist.size())));
	}

	/**
	 * @说明:置顶
	 * @author: zwy
	 */
	private void updata() {
		// ArrayList<MyShopListBean> list = new ArrayList<MyShopListBean>();
		// for (int i = 0; i < delist.size(); i++) {
		// int p = delist.get(i);
		// MyShopListBean bean = myShopListBeans.get(p);
		// list.add(bean);
		// }
		// myShopListBeans.removeAll(list);
		// myShopListBeans.addAll(list);
		// adapter.setGroup(myShopListBeans);
		// delist.clear();
	}

	/**
	 * @说明:删除
	 * @author: zwy
	 */
	private void delete() {
		if (delist.size() > 0) {
			ArrayList<MyShopListBean> list = new ArrayList<MyShopListBean>();
			for (int i = 0; i < delist.size(); i++) {
				int p = delist.get(i);
				MyShopListBean bean = myShopListBeans.get(p);
				list.add(bean);
			}
			myShopListBeans.removeAll(list);
			adapter.setGroup(myShopListBeans);
			delist.clear();
		}
	}

	/**
	 * @说明:下架
	 * @author: zwy
	 */
	private void out() {
		if (delist.size() > 0) {
			ArrayList<MyShopListBean> list = new ArrayList<MyShopListBean>();
			for (int i = 0; i < delist.size(); i++) {
				int p = delist.get(i);
				MyShopListBean bean = myShopListBeans.get(p);
				list.add(bean);
			}
			myShopListBeans.removeAll(list);
			adapter.setGroup(myShopListBeans);
			delist.clear();
		}
	}

	private OnItemClickListener skipItemListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			int realPos = position - ((ListView) parent).getHeaderViewsCount();
			MyShopListBean bean = myShopListBeans.get(realPos);
			Intent intent = new Intent(MyShopListActivity.this, MyShopActivity.class);
			intent.putExtra("shopId", bean.getShopId());
			intent.putExtra("merchantId", bean.getMerchantId());
			showActivity(MyShopListActivity.this, intent);
		}
	};
	private OnItemClickListener editItemListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		}
	};

	private void listNet() {
		FormResultRequest<ArrayList<MyShopListBean>> request = new FormResultRequest<ArrayList<MyShopListBean>>(UrlConstants.GETSHOPSTORELIST, listListener, this,
				new TypeToken<RequestResult<ArrayList<MyShopListBean>>>() {
				}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putStringTypeParam("userId", GlobalApp.userModel.getUserId());
		ajaxParams.putStringTypeParam("pageNo", String.valueOf(CURRENT_PAGE));
		ajaxParams.putStringTypeParam("pageSize", String.valueOf(PAGE_SIZE));
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	private void actionNet() {
		if (delist.size() > 0) {
			showLoadingDialog("");
			FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.GETSHOPUPDATE, actionListener, this, new TypeToken<RequestResult<String>>() {
			}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
			ajaxParams.putStringTypeParam("userId", GlobalApp.userModel.getUserId());
			ajaxParams.putStringTypeParam("chooseShopIds", getShopIds());
			ajaxParams.putStringTypeParam("typeId", actionFlag);
			request.setRequestParams(ajaxParams);
			executeRequest(request);
		} else {
			showToastMsg("您还未选中！");
		}
	}

	private String getShopIds() {
		int size = delist.size();
		StringBuilder shopIds = new StringBuilder();

		for (int i = 0; i < size; i++) {
			if (i != (size - 1)) {
				shopIds.append(String.format("%s,", myShopListBeans.get(delist.get(i)).getShopId()));
			} else {
				shopIds.append(myShopListBeans.get(delist.get(i)).getShopId());
			}
		}
		return shopIds.toString();
	}

	private Listener<RequestResult<ArrayList<MyShopListBean>>> listListener = new Listener<RequestResult<ArrayList<MyShopListBean>>>() {
		@Override
		public void onResponse(RequestResult<ArrayList<MyShopListBean>> arg0) {
			dismissLoadingDialog();
			ptrLv.onRefreshComplete();
			if (arg0.flag == 1 && arg0.getRs() != null && arg0.getRs().size() > 0) {
				if(CURRENT_PAGE == 1) {
					
					myShopListBeans = arg0.getRs();
				} else {
					myShopListBeans.addAll(arg0.getRs());
				}
				if(arg0.getRs().size() >= 10) {
					ptrLv.setMode(Mode.BOTH);
				} else {
					ptrLv.setMode(Mode.PULL_FROM_START);
				}
			}
			if (myShopListBeans.size()>0) {
				titleBarHelper.setRightMsg("编辑");
			}
			adapter.setGroup(myShopListBeans);
			// myShopListBeans.addAll(arg0.getRs());
			// adapter.setGroup(myShopListBeans);
		}
	};

	private Listener<RequestResult<String>> actionListener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			showToastMsg(arg0.msg);
			if (arg0.flag == 1) {
				if (actionFlag.equals("2")) {
					dismissLoadingDialog();
					delete();
				} else if (actionFlag.equals("3")) {
					dismissLoadingDialog();
					out();
				} else if (actionFlag.equals("1")) {
					delist.clear();
					listNet();
				}
			}
		}
	};

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> arg0) {
		CURRENT_PAGE = 1;
		listNet();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> arg0) {
		CURRENT_PAGE++;
		listNet();
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		dismissLoadingDialog();
		ptrLv.onRefreshComplete();
		if (CURRENT_PAGE > 1) {// 加载异常回退到当前页
			CURRENT_PAGE--;
		}
		String msg = "网络异常";
		if (error instanceof ServerFlagError) {
			msg = ((ServerFlagError) error).result.msg;
		} else if (error instanceof ServerJsonUnParseError) {
			try {
				String res = ((ServerJsonUnParseError) error).result;
				JSONObject jsonObject = new JSONObject(res);
				msg = jsonObject.getString("msg");
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			try {
				if (error.networkResponse != null && error.networkResponse.data != null) {
					msg = new String(error.networkResponse.data, "utf-8");
					if (TextUtils.isEmpty(msg)) {
						msg = "未知异常";
					}
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		showToastMsg(msg);
	}
	
	@Override
	protected void onResume() {
		listNet();
		super.onResume();
	}

}
